import sqlite3
from dayinfo import DayInfo

class DBInterface:

	_conn = None
	_name = None

	def __init__(self,name = None):
		if name:
			SetConnection(name)

	def SetConnection(self,name = None):
		if not name:
			return False

		self._name = name
		self._conn = sqlite3.connect("./.%s.db" % self._name)
		return True

	def GetConnectionParams(self):
		return {"name":self._name,"conn":self._conn}

	def GetCursor(self):
		return self._conn.cursor()

	def CreateTables(self):
		c = self.GetCursor()

		try:
			c.execute("""
				create table dayinfo(
					id integer primary key,
					daypic date,
					title text,
					link text);
			""")
		except sqlite3.OperationalError:
			"table already exists"

		self._conn.commit()

	def InsertDayInfo(self,dayinfo):
		c = self.GetCursor()
		c.execute("""
			insert into dayinfo values (
			%s,"%s","%s","%s");
			""" % (
				"NULL",
				dayinfo.date,
				dayinfo.title,
				dayinfo.link))
		self._conn.commit()

	def UpdateDayInfo(self,dayinfo):
		c = self.GetCursor()
		c.execute("""
			update dayinfo set
			daypic="%s",
			title="%s",
			link="%s" where
			id=%s """ % (
				dayinfo.date,
				dayinfo.title,
				dayinfo.link,
				dayinfo.id))
		self._conn.commit()

	def DeleteDayInfo(self,id):
		c = self.GetCursor()
		c.execute("""
			delete from dayinfo
			where id = %d
			""" % (id))
		self._conn.commit()

if __name__ == "__main__":
	pass
